<template>
  <div>
    <el-card>
      <!-- 搜索和操作区域 -->
      <div class="table-header">
        <div class="search-area">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入用户名或邮箱搜索"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <div class="action-area">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 用户表格 -->
      <el-table :data="users" style="width: 100%" v-loading="loading">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phoneNumber" label="电话" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleAssignRoles(scope.row)">
              分配角色
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="500px">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" :disabled="isEdit" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="电话" prop="phoneNumber">
            <el-input v-model="form.phoneNumber" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!isEdit">
            <el-input v-model="form.password" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '保存' : '创建' }}
          </el-button>
        </template>
      </el-dialog>

      <!-- 角色分配对话框 -->
      <el-dialog v-model="roleDialogVisible" title="分配角色" width="500px">
        <div class="role-assignment">
          <h4>为用户 "{{ selectedUser?.username }}" 分配角色：</h4>
          <el-checkbox-group v-model="selectedRoleIds">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id" :value="role.id">
              {{ role.name }} - {{ role.description }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <template #footer>
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoleAssignment" :loading="roleAssigning">
            保存
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { userApi, roleApi } from '@/api'

// 响应式数据
const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref()

// 角色分配相关
const roleDialogVisible = ref(false)
const roleAssigning = ref(false)
const selectedUser = ref(null)
const selectedRoleIds = ref([])
const allRoles = ref([])

// 表单数据
const form = reactive({
  username: '',
  email: '',
  phoneNumber: '',
  password: '',
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为8位', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur',
    },
  ],
}

// 生命周期
onMounted(() => {
  fetchUsers()
  fetchRoles()
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await userApi.getUsers({
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    users.value = res.items || []
    total.value = res.totalCount || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索用户
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    fetchUsers()
    return
  }

  loading.value = true
  try {
    const res = await userApi.searchUsers(searchKeyword.value)
    users.value = res || []
    total.value = users.value.length
  } catch (error) {
    ElMessage.error('搜索用户失败：' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  fetchUsers()
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    username: row.username,
    email: row.email,
    phoneNumber: row.phoneNumber || '',
    password: '',
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('不能删除管理员用户')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.username}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await userApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.response?.data?.message || error.message))
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value) {
      // 编辑用户
      const updateData = {
        username: form.username,
        email: form.email,
        phoneNumber: form.phoneNumber,
      }
      await userApi.updateUser(form.id, updateData)
      ElMessage.success('更新成功')
    } else {
      // 新增用户
      const createData = {
        username: form.username,
        email: form.email,
        phoneNumber: form.phoneNumber,
        password: form.password,
      }
      await userApi.addUser(createData)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    if (error !== false) {
      // 不是表单验证错误
      ElMessage.error(
        (isEdit.value ? '更新' : '创建') +
          '失败：' +
          (error.response?.data?.message || error.message),
      )
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    username: '',
    email: '',
    phoneNumber: '',
    password: '',
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 获取所有角色
const fetchRoles = async () => {
  try {
    const res = await roleApi.getAllRoles()
    allRoles.value = res.data || res || []
  } catch (error) {
    ElMessage.error('获取角色列表失败：' + (error.response?.data?.message || error.message))
  }
}

// 处理角色分配
const handleAssignRoles = async (user) => {
  selectedUser.value = user
  roleDialogVisible.value = true

  try {
    // 获取用户当前的角色
    const res = await userApi.getUserRoles(user.id)
    selectedRoleIds.value = (res.data || []).map((role) => role.id)
  } catch (error) {
    console.error('获取用户角色失败:', error)
    selectedRoleIds.value = []
  }
}

// 提交角色分配
const submitRoleAssignment = async () => {
  if (!selectedUser.value) return

  try {
    roleAssigning.value = true
    await userApi.assignRoles(selectedUser.value.id, selectedRoleIds.value)
    ElMessage.success('角色分配成功')
    roleDialogVisible.value = false
    fetchUsers() // 刷新用户列表
  } catch (error) {
    ElMessage.error('角色分配失败：' + (error.response?.data?.message || error.message))
  } finally {
    roleAssigning.value = false
  }
}
</script>

<style scoped>
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-area {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.role-assignment {
  padding: 10px 0;
}

.role-assignment h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.role-assignment .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.role-assignment .el-checkbox {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
}

.role-assignment .el-checkbox:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}
</style>
